package com.service.impl;

import com.entity.pojo.WrTeam;
import com.entity.pojo.WrTeamUser;
import com.entity.pojo.WrUser;
import com.entity.vo.TeamVo;
import com.mapper.WrTeamMapper;
import com.mapper.WrTeamUserMapper;
import com.service.TeamService;
import com.service.TeamUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service("teamService")
public class TeamServiceImp implements TeamService {

    @Resource
    private TeamUserService teamUserService;

    @Resource
    private WrTeamMapper wrTeamMapper;

    @Resource
    private WrTeamUserMapper teamUserMapper;

    @Override
    public List<TeamVo> listTeam() {
        return wrTeamMapper.listTeam();
    }

    @Override
    public int insertTeam(WrTeam wrTeam) {
        return wrTeamMapper.insert(wrTeam);
    }

    @Override
    public int updateTeam(TeamVo teamVo) {
        int res = wrTeamMapper.updateById(
                new WrTeam().setId(teamVo.getId())
                        .setTeamName(teamVo.getTeamName())
                        .setUpdateTime(LocalDateTime.now())
        );
        if (!teamVo.getUserList().isEmpty()) {
            teamUserService.cleanUserTeam(teamVo.getId());
            teamVo.getUserList().forEach(
                    userVo -> {
                        teamUserMapper.insert(
                                new WrTeamUser()
                                        .setUserId(userVo.getId())
                                        .setTeamId(teamVo.getId())
                                        .setCreateTime(LocalDateTime.now()));
                    }
            );
        }
        return res;
    }


    /**
     * 级联删除
     *
     * @param id
     * @return
     */
    @Override
    public int deleteTeam(int id) {
        return wrTeamMapper.updateById(new WrTeam().setDeleted(1).setId(id));
    }
}
